<?php
	require_once 'header.php';
	require_once 'navigation.php';
	//init session
	if (! isset($_SESSION['idStr']) || ! isset($_SESSION['numStr'])) {
		$_SESSION['idStr'] = '';
		$_SESSION['numStr'] = '';
	}
	//init cart
	$cart = new Cart($_SESSION['idStr'], $_SESSION['numStr']);
	//check operator
	$t = $_GET['t'];
	//add cart
	if ($t == 'add') {
		$cart->addCart($_GET['apid'], 1);
		$_SESSION['idStr'] = $cart->getIdStr();
		$_SESSION['numStr'] = $cart->getNumStr();
	}	
	//remove cart
	if ($t == 'remove') {
		$cart->removeCart($_GET['rpid']);
		$_SESSION['idStr'] = $cart->getIdStr();
		$_SESSION['numStr'] = $cart->getNumStr();
	}
	//update cart
	if ($t == 'update') {
		$changenum = $_GET['num'];
		if (! is_numeric($changenum) || intval($changenum) <= 0 || floor($changenum) != $changenum) {
			echo "<script>alert('购买数量只能为正整数！');</script>";
		} else {
			$cart->changeNum($_GET['upid'], $changenum);
			$_SESSION['idStr'] = $cart->getIdStr();
			$_SESSION['numStr'] = $cart->getNumStr();
		}
	}
	//clear cart
	if ($t == 'clearAll') {
		$cart->setCartNull();
		$_SESSION['idStr'] = $cart->getIdStr();
		$_SESSION['numStr'] = $cart->getNumStr();
	}
	//query product info
	$arrayIds = explode('@', $_SESSION['idStr']);
	$arrayNums = explode('@', $_SESSION['numStr']);
	$arrayCarInfos = array();
	$totalPrice = 0;
	for ($i = 0; $i < count($arrayIds); $i ++) {
		$productid = $arrayIds[$i];
		if ($productid != '') {
			$tmpArray = array();
			$productinfo = $adminDB->executeSQL("select id, fdName,fdLicense,fdPrice,fdVersion from ".$util->contentdbName().".tbProduct where id = ".$productid."", $connID);
			$tmpArray['id'] = $productinfo[0]['id'];
			$tmpArray['name'] = $productinfo[0]['fdName'];
			$tmpArray['version'] = $productinfo[0]['fdVersion'];
			$tmpArray['license'] = $productinfo[0]['fdLicense'];
			$tmpArray['price'] = $productinfo[0]['fdPrice'];
			$tmpArray['num'] = $arrayNums[$i];
			$tmpArray['smallTotalPrice'] = $productinfo[0]['fdPrice'] * $arrayNums[$i];
			$totalPrice += $tmpArray['smallTotalPrice'];
			array_push($arrayCarInfos, $tmpArray);
		}
	}
	$smarty->assign('arrayCarInfos', $arrayCarInfos);
	$smarty->assign('totalPrice', $totalPrice);
	//validate login
	if (isset($_SESSION['unc']) && $_SESSION['unc'] != '') {
		$smarty->assign('isLogin', 'T');
	} else {
		$smarty->assign('isLogin', 'F');
		if (isset($_SESSION['toUrl'])) {
			unset($_SESSION['toUrl']);
		}
		$_SESSION['toUrl'] = 'cart.php';
	}
	
	$smarty->display('cart.html');
	require_once 'contact.php';
	require_once 'footer.php';
?>